package org.example.scope;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义的ThreadLocal作用域
 * 每个线程维护一个Bean实例
 */
public class ThreadLocalScope implements Scope {
    
    private final ThreadLocal<Map<String, Object>> threadLocalScope = 
        ThreadLocal.withInitial(HashMap::new);
    
    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Map<String, Object> scope = threadLocalScope.get();
        Object object = scope.get(name);
        
        if (object == null) {
            object = objectFactory.getObject();
            scope.put(name, object);
            System.out.println("在线程 " + Thread.currentThread().getName() + 
                             " 中创建Bean: " + name + " -> " + object.hashCode());
        }
        
        return object;
    }
    
    @Override
    public Object remove(String name) {
        Map<String, Object> scope = threadLocalScope.get();
        return scope.remove(name);
    }
    
    @Override
    public void registerDestructionCallback(String name, Runnable callback) {
        // ThreadLocal作用域通常不需要销毁回调
    }
    
    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }
    
    @Override
    public String getConversationId() {
        return Thread.currentThread().getName();
    }
    
    /**
     * 清理当前线程的作用域
     */
    public void clearCurrentThreadScope() {
        threadLocalScope.remove();
    }
} 